<template>
    <div class="user-key" ref="container">
        <div class="user-key-content">
            <div class="user-key-add">
                <g-button type="primary" @click="openModal( 'add' )">新建密钥</g-button>
            </div>
            <table class="user-key-table">
                <thead class="user-key-table-head">
                    <tr>
                        <th class="user-key-table-key-head"><span>AccessKey</span></th>
                        <th class="user-key-table-type-head"><span>类型</span></th>
                        <th class="user-key-table-time-head"><span>更新时间</span></th>
                        <th class="user-key-table-trust-head"><span>信任域</span></th>
                        <th class="user-key-table-action-head"><span>操作</span></th>
                    </tr>
                </thead>
                <tbody class="user-key-table-body">
                    <tr v-for="row in list">
                        <td class="user-key-table-key"><div class="user-key-table-key-content"><input type="text" readonly :value="row.key"><i class="iconfont" :class="{
                            'icon-files': !copied || copiedKey !== row.key,
                            'icon-check copied': copied && copiedKey === row.key
                            }" @click="copy( row.key )"></i></div></td>
                        <td width="100" class="user-key-table-type"><span>{{ row.type }}</span></td>
                        <td width="100" class="user-key-table-time"><span>{{ row.updatedAt }}</span></td>
                        <td width="160" class="user-key-table-trust"><pre>{{ row.trust | trustFormat }}</pre></td>
                        <td width="190" class="user-key-table-action">
                            <g-button @click="openModal( 'update', row )">更新信任域</g-button>
                            <g-button type="danger" @click="removeKey( row )">删除</g-button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <transition name="g-modal-fade" @afterLeave="afterLeave">
            <div class="g-modal-wrapper private" v-show="modalVisible">
                <div class="g-modal user-key-modal">
                    <div class="g-modal-header user-key-modal-header">
                        <span>{{ modalType === 'add' ? '添加密钥' : '修改密钥' }}</span>
                        <i class="iconfont icon-close" @click="closeModal"></i>
                    </div>
                    <div class="g-modal-content user-key-modal-content">
                        <div class="user-key-modal-item" v-if="modalType === 'add'">
                            <p class="user-key-modal-item-title">类型</p>
                            <div class="user-key-modal-item-type">
                                <div class="user-key-type"
                                    :class="{ 'active': form.type === 'browser' }" 
                                    @click="form.type = 'browser'">用于浏览器应用</div>
                                <div class="user-key-type"
                                    :class="{ 'active': form.type === 'server' }"
                                    @click="form.type = 'server'">用于服务器应用</div>
                            </div>
                            <p class="user-key-modal-item-desc">该密匙用于{{ form.type === 'browser' ? '浏览器' : '服务器' }}应用需要访问API的情景</p>
                        </div>
                        <div class="user-key-modal-item">
                            <p class="user-key-modal-item-desc">在下面的信任域中，将允许访问API的网站URL按行输入（支持通配符）。<br>例如 “geohey.com/”</p>
                            <p class="user-key-modal-item-title">信任域<span>（留白表示对API访问不做限制，请谨慎使用）</span></p>
                            <textarea v-model="form.trust" spellcheck="false"></textarea>
                        </div>
                    </div>
                    <div class="g-modal-footer user-key-modal-footer">
                        <g-button type="primary" :loading="pending" @click="save">保存</g-button>
                    </div>
                </div>
            </div>
        </transition>
    </div>
</template>

<script>
import GButton from '@/components/common/g-button'
import { user as userAPI } from '@/api'
import Clipboard from 'clipboard'

export default {
    name: 'user-key',
    data () {
        return {
            list: [],
            modalType: 'add',
            modalVisible: false,
            copied: false,
            copiedKey: '',
            form: {
                key: null,
                type: 'browser',
                trust: null
            },
            pending: false
        }
    },
    mounted () {
        this.refresh();
    },
    computed: {

    },
    filters: {
        trustFormat ( val ) {
            if ( !val ) return '';
            let arr = val.split( '\n' );
            if ( arr.length > 3 ) {
                arr = arr.splice( 0, 3 );
                arr.push( '...' );
                return arr.join( '\n' );
            }
            return val;
        }
    },
    methods: {
        refresh () {
            let promise = userAPI.getAKList();

            promise.then( res => {

                this.list = res.data.data.map( item => {
                    let date = new Date( item.updated_at );
                    let year = date.getFullYear();
                    let month = date.getMonth() + 1;
                    let day = date.getDate();

                    return {
                        key: item.key,
                        type: item.type === 'browser' ? '浏览器应用' : '服务器应用',
                        updatedAt: `${ year }-${ month }-${ day }`,
                        trust: item.trust
                    }
                } )
            } ).catch( err => {} );
        },
        removeKey ( data ) {

            let key = data.key;

            this.$confirm('您确定删除此密钥吗？删除后使用该密钥的应用或分享都将失效', '提示', {
                parent: this.$refs.container,
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                confirmButtonType: 'danger',
                type: 'warning',
                beforeClose: ( action, instance, close ) => {
                    if ( action === 'confirm' ) {
                        instance.cancelButtonDisabled = true;
                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '执行中...';

                        userAPI.removeAK( key ).then( res => {
                            if ( res.data.code === 0 ) {
                                this.$message.success( '删除密钥成功' );
                                this.refresh();
                            } else {
                                this.$message.error( '删除密钥失败' );
                            }
                            close();
                        } ).catch( err => {
                            this.$message.error( '删除密钥失败' );
                            close();
                        } )
                    } else {
                        close ();
                    }
                }
            } )
        },
        openModal ( type, data ) {

            this.modalType = type;

            if ( type === 'update' ) {
                this.form.key = data.key;
                this.form.trust = data.trust;
            }

            this.modalVisible = true;

        },
        closeModal () {
            this.modalVisible = false;
        },
        afterLeave () {
            // 过渡结束时再重置，以免出现内容突然消失的情况
            this.form = {
                key: null,
                type: 'browser',
                trust: null
            }
        },
        save () {

            this.pending = true;

            let promise;
            let successMsg, errorMsg;

            if ( this.modalType === 'add' ) {

                promise = userAPI.addAK( this.form.type, this.form.trust );

                successMsg = '添加密钥成功';
                errorMsg = '添加密钥失败';

            } else {

                promise = userAPI.updateAKTrust( this.form.key, this.form.trust );

                successMsg = '更新信任域成功';
                errorMsg = '更新信任域失败';

            }

            promise.then( res => {
                if ( res.data.code === 0 ) {
                    this.$message.success( successMsg );
                    this.refresh();
                } else {
                    this.$message.error( errorMsg );
                }

                this.pending = false;
                this.closeModal();
            } ).catch( err => {

                this.$message.error( errorMsg);
                this.pending = false;
                this.closeModal();
            } )
        },
        copy ( key ) {

            this.copiedKey = key;

            const button = document.createElement( 'button' );

            const clipboard = new Clipboard( button, {
                text () {
                    return key;
                }
            } );

            clipboard.on( 'success', e => {
                e.clearSelection();
                clipboard.destroy();
                this.$message.success( '已复制到剪切板' );
                this.copied = true;
                setTimeout( () => {
                    this.copiedKey = '';
                    this.copied = false;
                }, 3000 )
            } );

            clipboard.on( 'error', e => {
                this.$message.error( '复制失败，请手动选择复制' )
            } );

            button.click();
        }
        
    },
    components: {
        GButton
    }
}
</script>

<style lang="scss">
@import 'common';
.user-key {
    .user-key-content {
        width: 100%;
        padding-bottom: 40px;
        margin-bottom: 20px;

        .user-key-add {
            margin-bottom: 20px;

            .g-button {
                padding: 0 20px;
            }
        }

        .user-key-table {
            max-width: 1200px;
            min-width: 880px;
            width: 100%;
            text-align: left;
            
            .user-key-table-head {
                font-weight: 600;
            }

            .user-key-table-body {
                padding-bottom: 60px;

                .user-key-table-key {
                    min-width: 400px;

                    .user-key-table-key-content {
                        width: 100%;
                        max-width: 400px;
                        position: relative;
                        display: inline-block;
                        > input {
                            width: 100%;
                            font-size: 12px;
                            height: 32px;
                            background-color: #f5f7fa;
                            color: #ADBCD9;
                            background-color: #f5f7fa;
                            border: 1px solid #e9edf4;
                            padding: 6px 28px 6px 12px;
                            border-radius: 4px;
                        }

                        > i {
                            cursor: pointer;
                            position: absolute;
                            right: 6px;
                            top: 50%;
                            transform: translateY(-50%);

                            &:hover {
                                color: $deepGray;
                            }

                            &.copied {
                                color: $success;
                                &:hover {
                                    color: $success;
                                }
                            }
                        }
                    }
                }

                .user-key-table-trust {
                    max-width: 160px;
                    max-height: 70px;

                    > pre {
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }

                .user-key-table-action {
                    min-width: 180px;
                    > .g-button {
                        margin-right: 16px;

                        &:last-child {
                            margin-right: 0;
                        }
                    }
                }

            }

            tr {

                > td, > th {
                    height: 70px;
                    overflow: hidden;
                    border-bottom: 1px solid $bdGray;
                    padding: 0 5px;
                }
            }

            // @media screen and (max-width: 580px) {
            //     .user-key-table-type,
            //     .user-key-table-time,
            //     .user-key-table-trust,
            //     .user-key-table-type-head,
            //     .user-key-table-time-head,
            //     .user-key-table-trust-head {
            //         display: none !important;
            //     }

            //     .user-key-table-key-head {
            //         min-width: 200px;
            //         display: inline-block;
            //     }

            //     .user-key-table-action-head {
            //         min-width: 100px;
            //         display: inline-block;
            //     }
            // }
        }
    }

    .user-key-modal {
        width: 660px;

        @media screen and (max-width: 580px) {
            width: 90%;
        }

        .user-key-modal-content {
            padding: 20px;

            .user-key-modal-item {
                margin-bottom: 30px;

                &:last-child {
                    margin-bottom: 0;
                }

                .user-key-modal-item-desc {
                    color: $gray;
                    font-size: $fontSizeSmall;
                    margin: 10px 0;
                    line-height: 26px;

                    @media screen and (max-width: 580px) {
                        display: none;
                    }
                }

                .user-key-modal-item-title {

                    color: $deepGray;
                    font-weight: 600;
                    margin-bottom: 10px;

                    > span {
                        color: $gray;
                        font-weight: 300;
                        font-size: 13px;
                    }
                }

                .user-key-modal-item-type {
                    width: 100%;
                    &::after {
                        @include clearfix();
                    }

                    .user-key-type {
                        width: 120px;
                        height: 28px;
                        line-height: 26px;
                        font-size: 13px;
                        text-align: center;
                        float: left;
                        border: 1px solid $bdGray;
                        cursor: pointer;
                        transition: all .1s;

                        &:first-child {
                            border-right: 0;
                        }
                        
                        &.active {
                            color: $white;
                            background-color: $primary;
                            border: 1px solid transparent;
                        }

                    }
                }

                > input, > textarea {
                    background-color: rgba( #d8d8d8, 0.1 );
                    border: 1px solid rgba( #303c46, 0.1 );
                    border-radius: 2px;
                    width: 100%;
                    padding: 6px 8px;
                }

                > input {
                    height: 36px;
                }

                > textarea {
                    resize: none;
                    height: 100px;
                }
            }
        }

        .user-key-modal-footer {
            text-align: center;
            padding: 20px 0 30px;

            .g-button {
                font-weight: 600;
                width: 150px;
            }
        }
    }
}
</style>
